import axios from 'axios'
import merge from 'lodash/merge'

const request = axios.create({
    //baseURL: `${import.meta.env.VITE_GATEWAY_BASE_URL}`,  //网关的 ip 和端口
    baseURL: `http://${import.meta.env.VITE_BASE_HOST}:${import.meta.env.VITE_GATEWAY_PORT}`,
    timeout: 1000 * 50,
    headers:{
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type'
    }
});

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
    let token = localStorage.getItem('token');
    if(typeof token !== "undefined"){
        config.headers['satoken'] = token;  // 设置请求头
    }
    return config
}, error => {
    console.log("前置连接异常")
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        //console.log('response 拦截器', res); // for debug
        return res;
    },
    error => {
        console.log('response 拦截器发现异常', error); // for debug
        return Promise.reject(error)
    }
);

export function getRequest(url, params, headers = {'Content-Type': 'application/json; charset=utf-8'}) {
    //时间戳参数
    let defaults = {'t': new Date().getTime()}
    params = merge(defaults, params)
    return new Promise((resolve, reject) => {
        request({
            url: url,
            method: 'get',
            params: params,
            header: headers
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    });
}

export function postRequest(url, datas, headers = {'Content-Type': 'application/json; charset=utf-8'}) {
    //时间戳参数
    datas['t'] = new Date().getTime()
    return new Promise((resolve, reject) => {
        request({
            url: url,
            method: 'post',
            data: datas,
            header: headers
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    });
}